package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     * @param dishDto
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //1.保存菜品
        this.save(dishDto);
        //2.保存口味
        //获取菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //将菜品id保存到口味中
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Transactional
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品的基本信息
        Dish dish = this.getById(id);
        //查询菜品对应的口味信息
        DishDto dishDto = new DishDto();
        //添加查询条件
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id",dish.getId());
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

        //将口味信息赋值到dishDto中
        dishDto.setFlavors(dishFlavorList);

        //copy
        BeanUtils.copyProperties(dish,dishDto);

        return dishDto;
    }

    /**
     * 修改菜品信息
     * @param dishDto
     */
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //1.更新菜品
        this.updateById(dishDto);
        //2.更新口味
        //先删除存在的口味
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper();
        queryWrapper.eq("dish_id",dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //3.再添加提交过来的口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //根据dishDto获取的ID来给口味赋值
        flavors.forEach(flavor-> flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }
}
